<template>
  <div class="page">
    <div class="form-wrapper">
      <!-- 顶部标题 -->
      <h2 class="form-title">
        {{ isLogin ? "登录" : "注册" }}
      </h2>
      <!-- 表单 -->
      <el-form :model="formData" :rules="formDataRules" ref="formEl">
        <el-form-item prop="name" label="">
          <el-input v-model="formData.name" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="pass" label="">
          <el-input v-model="formData.pass" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item prop="pass2" v-if="!isLogin" label="">
          <el-input v-model="formData.pass2" type="password" placeholder="确认密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-submit-btn" type="primary" @click="handleSubmit">
            {{ isLogin ? "登录" : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 其他选项 -->
      <div class="form-other-option">
        <!-- login option -->
        <div v-if="isLogin" class="login-option">
          <el-checkbox v-model="remember" label="记住账号"></el-checkbox>
          <el-link type="primary" @click="handleToRegister" :underline="false">注册</el-link>
        </div>
        <!-- register option -->
        <div v-else class="register-option">
          <el-link type="primary" @click="handleToLogin" :underline="false">&lt; 返回</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import { setToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
export default {
  name: "LoginView",
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (this.isLogin) {
        callback()
      } else if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.formData.pass) {
        callback(new Error('两次密码不匹配'))
      } else {
        callback()
      }
    }
    return {
      isLogin: true,
      formData: {
        name: "",
        pass: "",
        pass2: ""
      },
      formDataRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度限制为3~12', trigger: 'blur' }
        ],
        pass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度限制为6~18', trigger: 'blur' }
        ],
        pass2: [{ validator: validatePass2, trigger: 'blur' }]
      },
      remember: true
    }
  },
  mounted() {
    const name = localStorage.getItem('name') || ""
    this.formData.name = name
  },
  methods: {
    // 表单提交按钮-点击事件 
    handleSubmit() {
      if (!this.$refs.formEl) { return }

      this.$refs.formEl.validate((valid) => {
        if (valid) {
          console.log('submit!')
          if (this.isLogin) {
            // 执行登录 login
            this.login()
          } else {
            // 执行注册 register
            this.register()
          }
        } else {
          console.log('error submit!')
          return false
        }
      })
    },
    handleToRegister() {
      this.isLogin = false
    },
    handleToLogin() {
      this.isLogin = true
    },
    // 登录按钮触发事件
    login() {
      // 调用登录HTTP API
      api.token.login(this.formData.name, this.formData.pass)
        .then(result => {
          // 登录成功，初始化数据
          setToken(result.data.token)
          this.$store.dispatch('user/loadInfo')
          // 记住用户名
          if (this.remember) {
            localStorage.setItem('name', this.formData.name)
          }
          else {
            localStorage.removeItem('name')
          }

          ElMessage.success('登录成功')
          // FIXME: 登录成功返回到上一页
          this.$router.replace('/')
        }).catch(err => {
          console.error("login error:", err)
        })
    },
    // 注册按钮触发事件
    register() {
      api.user.register(this.formData.name, this.formData.pass).then(() => {
        ElMessage.success('注册成功')
        this.isLogin = true //跳转至登录页面
        // clear
        this.formData.pass = ""
        this.formData.pass2 = ""
      }).catch(err => {
        console.error('register error:', err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.form-wrapper {
  // max-width : 280px;
  width: 290px;
  padding-bottom: 100px;
}

.form-title {
  font-size: 14pt;
  font-weight: normal;
  text-align: center;
}

.form-submit-btn {
  width: 100%;
}

.login-option {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>